<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="物资名称" prop="materialId">
        <Aselect
          v-model="queryParams.materialId"
          :options="materialInfoList"
          placeholder="请选择物资"
          filterable
        ></Aselect>
      </el-form-item>
      <el-form-item label="入库日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeInboundDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="出库日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeOutboundDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['inventory:inventory:add']"
          >添加库存</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inventory:inventory:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:inventory:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['inventory:inventory:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="inventoryList"
      @selection-change="handleSelectionChange"
      :row-class-name="tableRowClassName"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        label="库存"
        align="center"
        prop="inventoryId"
      />
      <el-table-column
        label="物资名称"
        align="center"
        prop="materialId"
        width="120"
        #default="scope"
      >
        {{
          materialInfoList.find((res) => {
            return res.value === scope.row.materialId;
          })?.label
        }}
      </el-table-column>
      <el-table-column
        label="当前库存数量"
        align="center"
        prop="currentStock"
        width="180"
      />
      <el-table-column
        label="最低库存警戒线"
        align="center"
        prop="minimumStockAlert"
        width="180"
      />
      <el-table-column
        label="入库日期"
        align="center"
        prop="inboundDate"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.inboundDate, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="入库数量"
        align="center"
        prop="inboundQuantity"
      />
      <el-table-column
        label="出库日期"
        align="center"
        prop="outboundDate"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.outboundDate, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="出库数量"
        align="center"
        prop="outboundQuantity"
      />
      <el-table-column
        label="出入库原因"
        align="center"
        prop="remarks"
        width="180"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['inventory:inventory:edit']"
            >出入库</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['inventory:inventory:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物资名称库存对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="inventoryRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="物资名称" prop="materialId">
          <Aselect
            v-model="form.materialId"
            :options="materialInfoList"
            placeholder="请选择物资"
            filterable
          ></Aselect>
        </el-form-item>
        <el-form-item
          label="当前库存数量"
          prop="currentStock"
        >
          <el-input-number
            v-model="form.currentStock"
            placeholder="请输入当前库存数量"
            readonly
            disabled
          />
        </el-form-item>
        <el-form-item
          label="最低库存警戒线"
          prop="minimumStockAlert"
        >
          <el-input
            v-model="form.minimumStockAlert"
            placeholder="请输入最低库存警戒线"
          />
        </el-form-item>
        <el-form-item label="入库日期" prop="inboundDate">
          <el-date-picker
            clearable
            v-model="form.inboundDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择入库日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="入库数量"
          prop="inboundQuantity"
        >
          <el-input-number
            v-model="form.inboundQuantity"
            placeholder="请输入入库数量"
            @input="changeNum()"
          />
        </el-form-item>
        <el-form-item label="出库日期" prop="outboundDate">
          <el-date-picker
            clearable
            v-model="form.outboundDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择出库日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="出库数量"
          prop="outboundQuantity"
        >
          <el-input-number
            v-model="form.outboundQuantity"
            placeholder="请输入出库数量"
            @input="changeNum()"
          />
        </el-form-item>
        <el-form-item label="出入库原因" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Inventory">
import {
  listInventory,
  getInventory,
  delInventory,
  addInventory,
  updateInventory
} from "@/api/inventory/inventory";
import { listMaterialInfo } from "@/api/materialInfo/materialInfo";
import { onMounted, ref } from "vue";
import Aselect from "@/components/Select/Aselect.vue";

const { proxy } = getCurrentInstance();

const inventoryList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeInboundDate = ref([]);
const daterangeOutboundDate = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    materialId: null,
    currentStock: null,
    minimumStockAlert: null,
    inboundDate: null,
    inboundQuantity: null,
    outboundDate: null,
    outboundQuantity: null,
    remarks: null
  },
  rules: {
    materialId: [
      {
        required: true,
        message: "物资名称ID不能为空",
        trigger: "blur"
      }
    ],
    currentStock: [
      {
        required: true,
        message: "当前库存数量不能为空",
        trigger: "blur"
      }
    ],
    inboundQuantity: [
      {
        required: true,
        message: "入库数量不能为空",
        trigger: "blur"
      }
    ],
    outboundQuantity: [
      {
        required: true,
        message: "出库数量不能为空",
        trigger: "blur"
      }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 改变当前库存
function changeNum() {}

function tableRowClassName({ row }) {
  
  // 如果当前库存小于最低库存警戒线，返回警告类名
  if (row.currentStock < row.minimumStockAlert) {
  console.log(row.currentStock,row.minimumStockAlert);
  return "warning-row";
  }
  return "";
}

const materialInfoList = ref([]);
function getMaterialInfoList() {
  listMaterialInfo({
    pageNum: 1,
    pageSize: 100
  }).then((response) => {
    materialInfoList.value = response.rows.map((res) => {
      return {
        value: res.materialId,
        label: res.materialName
      };
    });
  });
}

/** 查询物资名称库存列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (
    null != daterangeInboundDate &&
    "" != daterangeInboundDate
  ) {
    queryParams.value.params["beginInboundDate"] =
      daterangeInboundDate.value[0];
    queryParams.value.params["endInboundDate"] =
      daterangeInboundDate.value[1];
  }
  if (
    null != daterangeOutboundDate &&
    "" != daterangeOutboundDate
  ) {
    queryParams.value.params["beginOutboundDate"] =
      daterangeOutboundDate.value[0];
    queryParams.value.params["endOutboundDate"] =
      daterangeOutboundDate.value[1];
  }
  listInventory(queryParams.value).then((response) => {
    inventoryList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

onMounted(() => {
  getList();
  getMaterialInfoList();
});

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    inventoryId: null,
    materialId: null,
    currentStock: 0,
    minimumStockAlert: null,
    inboundDate: null,
    inboundQuantity: 0,
    outboundDate: null,
    outboundQuantity: 0,
    remarks: null
  };
  proxy.resetForm("inventoryRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeInboundDate.value = [];
  daterangeOutboundDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.inventoryId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加物资库存";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _inventoryId = row.inventoryId || ids.value;
  getInventory(_inventoryId).then((response) => {
    form.value = response.data;
    form.value.inboundQuantity = 0;
    form.value.outboundQuantity = 0;
    open.value = true;
    title.value = "修改物资库存";
  });
}

/** 提交按钮 */
function submitForm() {
  const inboundQuantity = form.value.inboundQuantity - 0;
  const outboundQuantity = form.value.outboundQuantity - 0;
  const currentStock = form.value.currentStock - 0;
  form.value.currentStock =
    currentStock + inboundQuantity - outboundQuantity;
  if (form.value.currentStock < 0) {
    proxy.$modal.msgError("当前库存数量不能小于0");
  }
  proxy.$refs["inventoryRef"].validate((valid) => {
    if (valid) {
      if (form.value.inventoryId != null) {
        updateInventory(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInventory(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _inventoryIds = row.inventoryId || ids.value;
  proxy.$modal
    .confirm(
      '是否确认删除物资名称库存编号为"' +
        _inventoryIds +
        '"的数据项？'
    )
    .then(function () {
      return delInventory(_inventoryIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "inventory/inventory/export",
    {
      ...queryParams.value
    },
    `inventory_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style lang="scss">
/* 警告行的背景色 */
.el-table .warning-row {
  background-color: #fff0f0; /* 浅红色背景 */
}

/* 如果需要更醒目的效果，可以加上闪烁动画 */
@keyframes blink {
  0% {
    background-color: #fff0f0;
  }
  50% {
    background-color: #ffd6d6;
  }
  100% {
    background-color: #fff0f0;
  }
}

.el-table .warning-row {
  animation: blink 2s infinite;
}
</style>
